<import resource="classpath:alfresco/webscripts/org/alfresco/confluence/util/utils.js">

// Connect to remote Alfresco search service

// Prepare a remote connector to Alfreso service
var alfSearchServiceUrl = "/api/query";

var s = new Object();

if (args.sp == undefined) {
   s.startPage = 0;
}
else {
	s.startPage = parseInt(args.sp);
}

if (args.ps == undefined) {
	s.pageSize = 5;
}
else {
	s.pageSize = parseInt(args.ps);
}

s.startIndex = s.startPage * s.pageSize;

s.searchTerms = "";

var alfEndpoint = CMISUtils.endpoint.getEndpoint();

var conn = remote.connect(alfEndpoint);

//var ticket = CMISUtils.ticket.getTicket(conn);


try {

    if (args.q != null && args.q.length != 0) {

        var selectString = args.q;
        var query = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?><query xmlns:cmis=\"http://www.cmis.org/2008/05\"><statement>" + selectString + "</statement><pageSize>" + s.pageSize + "</pageSize></query>";
        s.query = query;

        // retrieve folder
        var queryResult = conn.post(stringUtils.urlEncodeComponent(alfSearchServiceUrl), query, "application/cmisquery+xml");

        if (queryResult.status == 200) {
           s.nodes = atom.toFeed(queryResult.response);

           s.totalResults = s.nodes.length;
           s.totalPages = Math.ceil(s.nodes.length / s.pageSize);
        } else {
           s.error = queryResult.response;
        }

    }

 } catch (e) {
 
 	s.error = "ERROR: " + e + "<br/><br/>";

    if (e.rhinoException != null) {
      
        var re = e.rhinoException;
 
        var stackTrace = re.getStackTrace() ;
        
        var out2 = " ";
        
        for each (n in stackTrace) {         
           out2 += n + "<br>&nbsp;&nbsp;&nbsp;";
        }
        
        s.error += out2 + "<br/>";
    }

 }

 model.s = s;
 
 model.endpoint = alfEndpoint;
 
 model.endpointurl = conn.getDescriptor().getEndpointUrl();
